﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using DevExpress.XtraSplashScreen;
using DevExpress.MailClient.Win;
using DevExpress.XtraEditors;

namespace PRO_DOCS.DocumentManagementSystem.CLIENT.WIN.Forms
{

    public partial class frmDepartmentFilesBulkInsert : BLL.WIN.Templates.DevxPermissionTemplate
    {
        //List<FileInfo> _selectedFiles = new List<FileInfo>();

        List<string> CURRENT_ARCHIVES_COPYING_FOLDERS
        {
            get;
            set;
        }

        bool _cONTINUE_UPLOADING;
        bool CONTINUE_UPLOADING
        {
            get { return _cONTINUE_UPLOADING; }
            set
            {
                _cONTINUE_UPLOADING = value;
                btnStartClose.Enabled = value;
            }
        }

        public bool FILES_ADDED
        { get; set; }

        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT _cURRENT_SELECTED_ARCHIVE_DEPARTMENT;
        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT CURRENT_SELECTED_ARCHIVE_DEPARTMENT
        {
            get { return _cURRENT_SELECTED_ARCHIVE_DEPARTMENT; }
            set
            {
                _cURRENT_SELECTED_ARCHIVE_DEPARTMENT = value;
                CURRENT_ARCHIVES_COPYING_FOLDERS = new List<string>();
                CONTINUE_UPLOADING = false;

                if (_cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID != 0)
                {


                    List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHE> aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES = _cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs.ToList();

                    for (int i = 0; i < aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES.Count; i++)
                    {
                        if (new DirectoryInfo(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).Exists)
                        {
                            CONTINUE_UPLOADING = true;
                            CURRENT_ARCHIVES_COPYING_FOLDERS.Add(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH);
                        }
                    }

                    if (!CONTINUE_UPLOADING)
                    {
                        XtraMessageBox.Show
                            (
                                string.Format("The storage media for the \"{0}\" department was not found.{1}Please make sure that you are connected to the network or contact your network administrator", _cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME, Environment.NewLine),
                                "Storage Media was not found",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning
                            );
                    }

                    #region DOCUMENT TYPES FOR THE CURRENT DEPARTMENT


                    ARCHIVE_DEPARTMENT_DOCUMENT_TYPES = new Dictionary<int, PRO_DOCS.DAL.Database.ARCHIVE_DOCUMENT_TYPE>();
                    List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_DOCUMENT_TYPE> cURRENT_DOCUMENT_FILES = _cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_DOCUMENT_TYPEs.ToList();

                    comboDocumentTypes.Properties.Items.BeginUpdate();
                    comboDocumentTypes.Properties.Items.Clear();
                    int nmbr = 0;
                    for (int i = 0; i < cURRENT_DOCUMENT_FILES.Count; i++)
                    {
                        if (!cURRENT_DOCUMENT_FILES[i].IS_DELETED.Value)
                        {
                            ARCHIVE_DEPARTMENT_DOCUMENT_TYPES.Add(nmbr, cURRENT_DOCUMENT_FILES[i].ARCHIVE_DOCUMENT_TYPE);
                            comboDocumentTypes.Properties.Items.Add(cURRENT_DOCUMENT_FILES[i].ARCHIVE_DOCUMENT_TYPE.ARCHIVE_DOCUMENT_TYPE_NAME);
                            nmbr++;
                        }
                    }

                    comboDocumentTypes.Properties.Items.EndUpdate();
                    comboDocumentTypes.SelectedIndex = -1;
                    #endregion
                }
            }
        }

        private PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER;
        [Browsable(false)]
        public PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE CURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER
        {
            get { return _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER; }
            set
            {
                _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER = value;
                if (CURRENT_SELECTED_ARCHIVE_DEPARTMENT != null)
                {
                    if (!CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID.Equals(_cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_DEPARTMENT_ID))
                    {
                        CURRENT_SELECTED_ARCHIVE_DEPARTMENT = _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_DEPARTMENT;
                    }
                }
                else
                {
                    CURRENT_SELECTED_ARCHIVE_DEPARTMENT = _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_DEPARTMENT;
                }

                txtDestinationFolder.Text = _cURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME;
            }
        }

        private FileInfo selectedFileInfo
        { get; set; }

        Dictionary<int, PRO_DOCS.DAL.Database.ARCHIVE_DOCUMENT_TYPE> ARCHIVE_DEPARTMENT_DOCUMENT_TYPES
        { get; set; }

        private int remaining;
        private int Remaining
        {
            get
            {
                return remaining;
            }
            set
            {
                remaining = value;
                lblStatus.Invoke(new MethodInvoker(delegate
                    {
                        lblStatus.Text = string.Format("{0} Remainings", value.ToString());
                    }));
            }
        }

        private int Total
        { set { lblTotal.Text = string.Format("{0} Total", value); } }

        private int succeded;
        private int Succeded
        {
            get { return succeded; }
            set
            {
                succeded = value;
                lblSuccess.Invoke(new MethodInvoker(delegate
                    {
                        lblSuccess.Text = string.Format("{0} Success", value.ToString());
                    }));
            }
        }

        private int error;
        private int Error
        {
            get { return error; }
            set
            {
                error = value;
                lblErrors.Invoke(new MethodInvoker(delegate
                    {
                        lblErrors.Text = string.Format("{0} Errors", value.ToString());
                    }));
                lblWarnings.Invoke(new MethodInvoker(delegate
                    {
                        lblWarnings.Text = string.Format("{0} Warnings", value.ToString());
                    }));
            }
        }

        public frmDepartmentFilesBulkInsert()
        {
            InitializeComponent();
            CURRENT_SELECTED_ARCHIVE_DEPARTMENT = new DAL.Database.ARCHIVE_DEPARTMENT();
            FILES_ADDED = false;
        }

        private void MonthlyReportsBulkInsert_Load(object sender, EventArgs e)
        {

            SplashScreenManager.ShowForm(typeof(DevExpress.MailClient.Win.Forms.wfMain), true, true);
            ucFolderStructureTree1.CURRENT_SELECTED_VIEW_MODE = ucFolderStructureTree.FolderStructureViewModes.FolderSelection;
            ucFolderStructureTree1.BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE();
            pnlStatus.Visible = false;
            SplashScreenManager.CloseForm();
        }

        private void btnOpenOriginalFile_Click(object sender, EventArgs e)
        {

            SplashScreenManager.ShowForm(typeof(DevExpress.MailClient.Win.Forms.wfMain), true, true);
            List<DevExpress.MailClient.Win.Data.UploadedPhysicalFiles> selectedFilePathes = new List<DevExpress.MailClient.Win.Data.UploadedPhysicalFiles>();

            OpenFileDialog openFileDialogObj = new OpenFileDialog();
            openFileDialogObj.Title = "Choose Department Files.";
            openFileDialogObj.Multiselect = true;
            openFileDialogObj.FilterIndex = 1;
            openFileDialogObj.RestoreDirectory = true;
            if (openFileDialogObj.ShowDialog() == DialogResult.OK)
            {
                gridControl1.DataSource = null;

                txtFileLocationPath.Text = new FileInfo(openFileDialogObj.FileNames[0]).DirectoryName;

                string[] selectedFiles = openFileDialogObj.FileNames;

                #region Set the labels
                Remaining = selectedFiles.Length;
                Total = selectedFiles.Length;
                Error = 0;
                Succeded = 0;
                #endregion

                for (int i = 0; i < selectedFiles.Length; i++)
                {
                    string fullDownloadReportPath = selectedFiles[i];
                    selectedFileInfo = new FileInfo(fullDownloadReportPath);

                    DevExpress.MailClient.Win.Data.UploadedPhysicalFiles single_uploaded_physical_file = new DevExpress.MailClient.Win.Data.UploadedPhysicalFiles();
                    single_uploaded_physical_file.CheckedFile = true;
                    single_uploaded_physical_file.FileId = Guid.NewGuid();
                    single_uploaded_physical_file.FileInfo = selectedFileInfo;
                    single_uploaded_physical_file.UploadingMessage = string.Empty;
                    single_uploaded_physical_file.CurrentIcon = "none";
                    selectedFilePathes.Add(single_uploaded_physical_file);
                }

                gridControl1.DataSource = selectedFilePathes;
            }
            SplashScreenManager.CloseForm();
        }

        private void btnStartClose_Click(object sender, EventArgs e)
        {
            //1. switch view
            pnlStatus.Visible = true;
            pnlStatus.Refresh();

            tblExcelUploads.Visible = false;
            tblExcelUploads.Refresh();

            bgWorker.RunWorkerAsync();
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pictureBox1.Image = (Error > 0) ? DevExpress.MailClient.Win.Properties.Resources.breakingchange_32x32 : DevExpress.MailClient.Win.Properties.Resources.apply_32x32;
            btnStartClose.Text = "Start";
            btnStartClose.Enabled = false;
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {

            SplashScreenManager.ShowForm(typeof(DevExpress.MailClient.Win.Forms.wfMain), true, true);
            string errorMessage = string.Empty;
            string imageKey = string.Empty;
            btnStartClose.Invoke(new MethodInvoker(delegate
                {
                    btnStartClose.Text = "Close";
                }));



            {
                gridControl1.Invoke(new MethodInvoker(delegate
                {
                    for (int i = 0; i < gridView1.DataRowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gcCurrentStatus, "progress");
                        DevExpress.MailClient.Win.Data.UploadedPhysicalFiles uploadedPhysicalFiles = gridView1.GetRow(i) as DevExpress.MailClient.Win.Data.UploadedPhysicalFiles;


                        bool fileUploaded = false;
                        //1. Copy the file to the Folder
                        if (uploadedPhysicalFiles.CheckedFile)
                        {
                            //the new fileId to be named with
                            string newCreatedPhysicalFileName = uploadedPhysicalFiles.FileId.ToString();
                            //the original file path
                            FileInfo currentConsumedFile = uploadedPhysicalFiles.FileInfo;
                            //a. copy the file

                            for (int fc = 0; fc < CURRENT_ARCHIVES_COPYING_FOLDERS.Count; fc++)
                            {
                                try
                                {
                                    currentConsumedFile.CopyTo(Path.Combine(CURRENT_ARCHIVES_COPYING_FOLDERS[fc], newCreatedPhysicalFileName));
                                    fileUploaded = true;
                                    break;
                                }
                                catch (Exception ex)
                                {
                                    gridView1.SetRowCellValue(i, gcMessage, ex.Message);
                                }
                            }

                            if (fileUploaded)
                            {
                                FILES_ADDED = true;
                                //2. ADD the file table
                                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE aRCHIVE_DEPARTMENT_FILE = new DAL.Database.ARCHIVE_DEPARTMENT_FILE();
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID = Guid.NewGuid();
                                //--------->aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID;
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = CURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID;
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME = currentConsumedFile.Name.Replace(currentConsumedFile.Extension, string.Empty);
                                //---------->get the document type
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DOCUMENT_TYPE_ID = ARCHIVE_DEPARTMENT_DOCUMENT_TYPES[comboDocumentTypes.SelectedIndex].ARCHIVE_DOCUMENT_TYPE_ID;
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE = BLL.WIN.Utilities.FileType.GenerateRandomBarcode();
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE = DateTime.Now;
                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED = false;
                                aRCHIVE_DEPARTMENT_FILE.IS_DELETED = false;

                                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILESInsert
                                    (
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE.Value,
                                    BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DOCUMENT_TYPE_ID.Value,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NOTES,
                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED.Value,
                                    aRCHIVE_DEPARTMENT_FILE.IS_DELETED.Value
                                    );

                                //1. ADD The file history
                                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY aRCHIVE_DEPARTMENT_FILE_HISTORY = new DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY();
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = uploadedPhysicalFiles.FileId;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID = aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID;
                                //aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = Guid.NewGuid();
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID = 1;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME = currentConsumedFile.Name;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION = currentConsumedFile.Extension;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID = PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE = currentConsumedFile.Length;
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE = DateTime.Now;

                                aRCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED = false;


                                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_HISTORYInsert
                                (
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID.Value,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID.Value,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID.Value,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.Value,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_NOTES,
                                aRCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED.Value);


                                gridView1.SetRowCellValue(i, gcCurrentStatus, "done");
                            }
                            else
                            {

                                gridView1.SetRowCellValue(i, gcMessage, "There was error copying the file to the destination folder, please make sure that there is enough desk space or you are connected the network path successfully.");
                                gridView1.SetRowCellValue(i, gcCurrentStatus, "alert");
                            }

                        }
                        else
                        {
                            gridView1.SetRowCellValue(i, gcCurrentStatus, "removed");
                        }

                        if (fileUploaded)
                            Succeded++;
                        else
                            Error++;
                    }

                }));
            }

            SplashScreenManager.CloseForm();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dtepkrAccountMonth_ValueChanged(object sender, EventArgs e)
        {

        }

        private void btnChooseDestinationFolder_Click(object sender, EventArgs e)
        {
            tblFolderChoosing.Visible = true;
        }

        private void btnChooseFolder_Click(object sender, EventArgs e)
        {
            if (ucFolderStructureTree1.CURRENT_SELECTED_ApplicationStructureType.Equals(ApplicationStructureTypes.Folder))
            {
                CURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER = ucFolderStructureTree1.CURRENT_SELECTED_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE;

                tblFolderChoosing.Visible = false;
            }
            else
            {
                XtraMessageBox.Show("You've to select a folder to continue, please select a folder and try again", "Folder not selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            tblFolderChoosing.Visible = false;
        }
    }
}
